<template>
    <div style="width: 100vw;height: 100vh;background-color: #2d3a4b;">
        <div style="position: absolute;top: 230px;left: 500px;width: 900px;">
            <el-form ref="ruleFormRef" label-width="100px" :model="ruleForm" :rules="rules" style="max-width: 460px">
                <el-form-item>
                    <h1 style="width:100%;text-align: center;color: white;">厚溥云课堂</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" v-model="ruleForm.username" placeholder="用户名" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" show-password v-model="ruleForm.password" placeholder="密码" />
                </el-form-item>
                <el-form-item>
                    <el-button :loading="loading" @click="submitForm(ruleFormRef)" type="primary" style="width: 100%;">
                        登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <!--  -->

</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import loginApi from '../api/login'
import { useRouter } from 'vue-router';
import {useUserInfo} from '../stote'
const userStore=useUserInfo()
const router = useRouter()

// 按钮加载状态
const loading = ref(false)

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    username: '',
    password: '',
})

const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
        },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            // console.log('submit!')
            // 调用api
            loginApi.login(ruleForm.username, ruleForm.password).then(res => {
                loading.value = false
                // 登陆成功

                // 存储密钥
                localStorage.setItem('member_token', res.data.token)
                


                // 跳转首页
                router.push('/')
            }).then(()=>{
                // 请求获取用户信息的api
                loginApi.getInfo().then(res=>{
                    console.log(res.data);
                    // 保存当前登录成功的用户信息
                    userStore.userInfo.userName=res.data.name
                })
            }).catch(err => {
                loading.value = false
                console.log(err)
            })
        } else {

            console.log('error submit!', fields)
        }
    })
}
</script>
  